package com.paipaideli.ui.price;

/**
 * Created by 出价 on 2019/8/31.
 */

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.BuildConfig;
import com.paipaideli.MyApplication;
import com.paipaideli.R;
import com.paipaideli.alipay.PayResult;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.PullRefreshView;
import com.paipaideli.common.utils.DateUtil;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.CircleImageView;
import com.paipaideli.common.views.CommonDialogView;
import com.paipaideli.common.views.DownIntoPriceView;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.mine.head.InvestActivity;
import com.paipaideli.ui.mine.order.OrderActivity;
import com.paipaideli.ui.price.bean.IntoBean;
import com.paipaideli.ui.price.bean.Message;
import com.paipaideli.ui.price.layout.WrapContentLinearLayoutManager;
import com.paipaideli.webSocket.JWebSocketClient;

import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PriceActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout topBack;
    @BindView(R.id.top_title)
    TextView topTitle;

    @BindView(R.id.tv_down_time)
    DownIntoPriceView tv_down_time;
    @BindView(R.id.image_down_time)
    ImageView image_down_time;

    @BindView(R.id.imame_price_head)
    CircleImageView imamePriceHead;
    @BindView(R.id.tv_price_name)
    TextView tvPriceName;
    @BindView(R.id.tv_price_now)
    TextView tvPriceNow;
    @BindView(R.id.tv_price_one)
    TextView tvPriceOne;
    @BindView(R.id.lin_price_name)
    LinearLayout linPriceName;
    @BindView(R.id.image_good_head)
    ImageView imageGoodHead;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_good_qpprice)
    TextView tvGoodQpprice;
    @BindView(R.id.tv_good_scprice)
    TextView tvGoodScprice;
    @BindView(R.id.tv_good_oneprice)
    TextView tvGoodOneprice;
    @BindView(R.id.lin_price_product)
    RelativeLayout linPriceProduct;
    @BindView(R.id.recycleview_price)
    PullRefreshView recycleviewPrice;
    @BindView(R.id.btn_price_to)
    Button btnPriceTo;

    private List<Message> msgList = new ArrayList<>();
    private PriceAdapter adapter;

    private String goodId;
    private long startTime;
    private long endTime;
    private long nowTime;
    private String goodImage;
    private String goodName;
    private String qpPrice;
    private String scPrice;
    private String onePrice;
    private String fdPrice;

    private String roomToken;
    private String token;

    private JWebSocketClient client;

    private boolean isconnet = false;
    private JSONObject json = null;
    private String status = "";
    private String isGet = "0";
    private String msgType = "";

    private int frist = 0;
    private Vibrator vibrator;

    private static final int SDK_PAY_FLAG = 1;
    private String outTradeNo;
    NetWorkStateReceiver netWorkStateReceiver;
    private Message msg;
    private CommonDialogView dialog;
    private int types;

    private boolean isdialog = false;
    private boolean isclick = false;

    @SuppressLint("HandlerLeak")
    private Handler mHandlers = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        AlipayQuery();//支付宝回调查询
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(PriceActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            Toast.makeText(PriceActivity.this, "支付取消", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(PriceActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public int getContentView() {
        return R.layout.activity_price;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        topTitle.setText("当前拍场");
        //返回
        topBack.setOnClickListener(o ->
                finish()
        );
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        recycleviewPrice.setEnableRefresh(true);
        recycleviewPrice.setEnableLoadmore(true);
        recycleviewPrice.setRefreshFalse();
        adapter = new PriceAdapter();
        WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(this);
        recycleviewPrice.setLayoutManager(linearLayoutManager);
        recycleviewPrice.setAdapter(adapter);

        initDate();//初始化页面展示

        //点击按钮出价
        RxView.clicks(btnPriceTo)
                .subscribe(v -> {
                    if (!isdialog) {//多次弹框
                        if (isclick) {//是否可以点击出价按钮
                            intoPrice();
                        }
                    }
                });
    }

    //出价按钮
    private void intoPrice() {
        try {
            vibrator.vibrate(2);//vibrate有多个重载方法，可以实现多种效果，这个括号中是持续震动时间
            if (StringUtil.isEmpty(status)) {
                return;
            } else {
                if (status.equals("1")) {//正常出价
                    if (msgType.equals("0") || StringUtil.isEmpty(msgType)) {
                        if (isconnet) {//是否请求到ws
                            try {
                                Map map = new HashMap();
                                map.put("token", token);
                                map.put("roomToken", roomToken);
                                map.put("msgType", "1");
                                String param = JSON.toJSONString(map);
                                client.send(param);//发送数据给服务器
                            } catch (Exception e) {
                                e.getMessage();
                            }
                        } else {
                            WS();//重新请求房间号连接ws
                        }
                    } else if (msgType.equals("1")) {
                        showAuhn();
                    } else {
                        ToastUtil.show("当前拍场已到最高价！");
                    }
                } else if (status.equals("2")) {//拍场未开始
                    showStart();
                } else if (status.equals("3")) {//拍场已结束，倒计时结束
                    showFinish();
                } else if (status.equals("4") && !isconnet) {//拍场已到最高价
                    showFinish();
                } else if (status.equals("5")) {//拍场商品已做修改
                    showDel();
                }
            }
        } catch (Exception e) {
            getRoomTooke();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        System.gc();
        msgList.clear();
        initInto();//进入拍场
    }

    private void initDate() {
        //商品出价数据
        goodId = getIntent().getStringExtra("goodId");
        goodImage = getIntent().getStringExtra("goodImage");
        goodName = getIntent().getStringExtra("goodName");
        qpPrice = getIntent().getStringExtra("qpPrice");
        scPrice = getIntent().getStringExtra("scPrice");
        onePrice = getIntent().getStringExtra("onePrice");
        fdPrice = getIntent().getStringExtra("fdPrice");
        linPriceName.setVisibility(View.GONE);
        linPriceProduct.setVisibility(View.VISIBLE);
        ImageUtil.displayImage(goodImage, imageGoodHead);
        tvGoodName.setText(goodName);
        FastData.setGoodname(goodName);
        FastData.setGoodimage(goodImage);
        FastData.setGoodprice(onePrice);
        tvGoodQpprice.setText("起拍价：￥" + qpPrice);
        tvGoodScprice.setText("封顶价：￥" + fdPrice);
        tvGoodOneprice.setText("加价幅度：￥" + onePrice);
    }

    //进入拍场
    private void initInto() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("aid", goodId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().into(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    status = request.status;
                    isclick = true;
                    if (request.code.equals("200")) {
                        roomToken = request.data.roomToken;
                        token = request.data.token;
                        startTime = request.data.startTime;
                        endTime = request.data.endTime;
                        showTime();
                        if (status.equals("4")) {//拍场已到最高价，倒计时还没有到
                            priceFinish(request);
                        } else {
                            if (roomToken != null && !StringUtil.isEmpty(roomToken)) {
                                initSocketClient();//请求ws
                            }
                        }
                    } else {
                        //请求返回statu返回5
                        if (status.equals("5")) {//拍品已经修改
                            showDel();
                        }
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    //显示倒计时时间
    private void showTime() {
        //将前一个缓存清除
        if (tv_down_time != null) {
            tv_down_time.cancel();
        }
        nowTime = DateUtil.getCurTimeLong();
        if (startTime - nowTime > 0) {//拍场未开始
            tv_down_time.init(startTime - nowTime, endTime - startTime, 0, new DownIntoPriceView.CouponDownInterface() {
                @Override
                public void runDown() {
                    status = "4";
                    //倒计时结束置灰
                    tv_down_time.init(0, 0, 3, new DownIntoPriceView.CouponDownInterface() {
                        @Override
                        public void runDown() {
                        }

                        @Override
                        public void runText(String timer, int type) {
                        }
                    });
                }

                @Override
                public void runText(String timer, int type) {
                    types = type;
                    if (type == 0) {
                        image_down_time.setBackgroundResource(R.mipmap.icon_price_djsok);
                    } else {
                        image_down_time.setBackgroundResource(R.mipmap.icon_price_djsno);
                    }
                    if (timer.equals("000001")) {
                        if (status.equals("2")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getRoomTooke();
                                }
                            });
                        }
                    }
                }
            });
        } else if (startTime - nowTime < 0 && endTime - nowTime > 0) {//拍场进行时
            tv_down_time.init(0, endTime - nowTime, 1, new DownIntoPriceView.CouponDownInterface() {
                @Override
                public void runDown() {
                    status = "4";
                    tv_down_time.init(0, 0, 3, new DownIntoPriceView.CouponDownInterface() {
                        @Override
                        public void runDown() {
                        }

                        @Override
                        public void runText(String timer, int type) {
                        }
                    });
                }

                @Override
                public void runText(String timer, int type) {
                    if (type == 0) {
                        image_down_time.setBackgroundResource(R.mipmap.icon_price_djsok);
                    } else {
                        image_down_time.setBackgroundResource(R.mipmap.icon_price_djsno);
                    }
                }
            });
        } else if (endTime - nowTime <= 0) {//拍场结束时
            if (!status.equals("5")) {
                showFinish();
            }
        }
    }

    //获取房间号
    private void getRoomTooke() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("aid", goodId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().take(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    status = request.status;
                    if (request.code.equals("200")) {
                        roomToken = request.data.roomToken;
                        token = request.data.token;
                        if (roomToken != null && !StringUtil.isEmpty(roomToken)) {
                            initSocketClient();
                        }
                    } else {
                        if (status.equals("5")) {
                            showDel();
                        }
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    //拍场已到最高价，倒计时还没有到
    private void priceFinish(IntoBean request) {
        linPriceName.setVisibility(View.VISIBLE);
        linPriceProduct.setVisibility(View.GONE);
        ImageUtil.displayImage(request.data.avatar, imamePriceHead);
        tvPriceName.setText(request.data.userName);
        tvPriceNow.setText("￥" + request.data.curPrice);
        tvPriceOne.setText("￥" + onePrice);
        Message msg = new Message();
        msg.setActionTimeStr(request.data.actionTimeStr);
        msg.setAvatar(request.data.avatar);
        msg.setBounty(request.data.bounty);
        msg.setIsGet(request.data.isGet);
        msg.setPrice(request.data.curPrice);
        msg.setUserId(request.data.userId);
        msg.setUserName(request.data.userName);
        msgList.add(msg);
        //当有新消息时，调用notifyItemInserted方法刷新listview中的显示
        adapter.notifyDataSetChanged();
        //将listview定位到最后一行
        recycleviewPrice.scrollToPosition(msgList.size() - 1);
        if (status.equals("4")) {
            showFinish();
        }
    }

    //未连接到ws
    private void WS() {
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("未连接到拍价服务器，是否重新连接！")
                .setTitle("温馨提示")
                .setPositive("重连")
                .setNegtive("取消")
                .setSingle(false).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                try {
                    getRoomTooke();
                } catch (Exception e) {
                    e.getMessage();
                }
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        }).show();
    }

    //拍品未开始
    private void showStart() {
        isdialog = true;
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("当前拍场还未开始！")
                .setTitle("温馨提示")
                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                isdialog = false;
                dialog.dismiss();
                if (types == 1) {
                    getRoomTooke();
                }
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();

            }
        }).show();
    }

    //拍品已删除
    private void showDel() {
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("拍品已被重新编辑，请重新选择拍场！")
                .setTitle("温馨提示")
                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                MainActivity.openSingleTop(PriceActivity.this);
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        }).show();
    }

    //拍场已结束
    private void showFinish() {
        isdialog = true;
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("当前拍场已结束，请重新选择拍场！")
                .setTitle("温馨提示")
                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                isdialog = false;
                dialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();

            }
        }).show();
    }

    //拍场已拍中
    private void showHomeOrder() {
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("恭喜您拍中了！")
                .setTitle("温馨提示")
                .setPositive("回首页")
                .setNegtive("去订单")
                .setSingle(false).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                MainActivity.openSingleTop(PriceActivity.this);
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
                Intent intent = new Intent(getCurrentActivity(), OrderActivity.class);
                intent.putExtra("whichOrder", "1");
                startActivity(intent);
            }
        }).show();
    }

    //支付宝预授权
    private void showAuhn() {
        dialog = new CommonDialogView(PriceActivity.this);
        dialog.setMessage("您尚未有参拍资格，请去充值押金（300元）或者开通支付宝预授权获得参拍资格")
                .setTitle("温馨提示")
                .setPositive("支付宝授权")
                .setNegtive("去充值")
                .setSingle(false).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                auth();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
                MyApplication.isAlipay = 1;
                Intent intent = new Intent(PriceActivity.this, InvestActivity.class);
                startActivity(intent);
            }
        }).show();
    }

    public class PriceAdapter extends RecyclerView.Adapter<PriceAdapter.ViewHolder> {

        @Override
        public PriceAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(PriceActivity.this).inflate(R.layout.item_price, null);
            inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(PriceAdapter.ViewHolder viewHolder, final int position) {
            Message msg = null;
            try {
                if (msgList.size() > position) {
                    msg = msgList.get(position);
                } else {
                    return;
                }
                //判断消息类型 如果是收到的消息 显示左边的消息布局，隐藏右边的消息布局
                if (msgList.size() > 0) {
                    if (position == 0) {
                        viewHolder.lin_price_look.setVisibility(View.VISIBLE);
                    } else {
                        viewHolder.lin_price_look.setVisibility(View.GONE);
                    }
                    viewHolder.tvPriceTime.setText(msgList.get(position).getActionTimeStr());
                    if (!msg.getUserId().equals(token)) {
                        viewHolder.linLeft.setVisibility(View.VISIBLE);
                        viewHolder.linRight.setVisibility(View.GONE);
                        ImageUtil.displayImage(msgList.get(position).getAvatar(), viewHolder.imagePriceLeft);
                        viewHolder.tvPriceLeftName.setText(msgList.get(position).getUserName());
                        viewHolder.tvPriceLeftPrice.setText(" 出价" + msgList.get(position).getPrice() + "元，将获得" + Float.valueOf(msgList.get(position).getBounty()) + "元的奖励金 ");
                        //viewHolder.tvPriceLeftPrice.setText(" 出价"  + "888元，将获得" + "888元的奖励金 ");
                        //判断消息类型 如果是发送的消息 显示右边的消息布局，隐藏左边的消息布局
                    } else if (msg.getUserId().equals(token)) {
                        viewHolder.linLeft.setVisibility(View.GONE);
                        viewHolder.linRight.setVisibility(View.VISIBLE);
                        ImageUtil.displayImage(msgList.get(position).getAvatar(), viewHolder.imagePriceRight);
                        viewHolder.tvPriceRightName.setText(msgList.get(position).getUserName());
                        viewHolder.tvPriceRightPrice.setText(" 出价" + msgList.get(position).getPrice() + "元，将获得" + Float.valueOf(msgList.get(position).getBounty()) + "元的奖励金 ");
                    }
                    if (msg.getIsGet().equals("1")) {
                        viewHolder.lin_price_success.setVisibility(View.VISIBLE);
                        ImageUtil.displayImage(FastData.getGoodimage(), viewHolder.priceImageSuccess);
                        viewHolder.tvPriceSuccessName.setText(FastData.getGoodname());
                        viewHolder.tvPriceSuccessPrice.setText("￥" + msgList.get(position).getPrice());
                        viewHolder.tvPriceSuccessPenson.setText("成交人：" + msgList.get(position).getUserName());
                    } else {
                        viewHolder.lin_price_success.setVisibility(View.GONE);
                    }
                } else {
                    return;
                }
            } catch (Exception e) {
                e.getMessage();
            }
            //点击查看历史记录
            RxView.clicks(viewHolder.lin_price_look)
                    .throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe(o -> {
                        Intent intent = new Intent(PriceActivity.this, HistoryActivity.class);
                        intent.putExtra("token", token);
                        intent.putExtra("id", goodId);
                        startActivity(intent);
                    }, throwable -> {
                    });
        }

        @Override
        public int getItemCount() {
            return msgList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.lin_price_look)
            LinearLayout lin_price_look;
            @BindView(R.id.tv_price_time)
            TextView tvPriceTime;
            @BindView(R.id.image_price_left)
            CircleImageView imagePriceLeft;
            @BindView(R.id.tv_price_left_name)
            TextView tvPriceLeftName;
            @BindView(R.id.tv_price_left_price)
            TextView tvPriceLeftPrice;
            @BindView(R.id.lin_left)
            LinearLayout linLeft;
            @BindView(R.id.image_price_right)
            CircleImageView imagePriceRight;
            @BindView(R.id.tv_price_right_name)
            TextView tvPriceRightName;
            @BindView(R.id.tv_price_right_price)
            TextView tvPriceRightPrice;
            @BindView(R.id.lin_right)
            LinearLayout linRight;
            @BindView(R.id.lin_price_success)
            LinearLayout lin_price_success;
            @BindView(R.id.price_image_success)
            ImageView priceImageSuccess;
            @BindView(R.id.tv_price_success_name)
            TextView tvPriceSuccessName;
            @BindView(R.id.tv_price_success_price)
            TextView tvPriceSuccessPrice;
            @BindView(R.id.tv_price_success_penson)
            TextView tvPriceSuccessPenson;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 初始化websocket连接
     */
    private void initSocketClient() {
        URI uri = URI.create(BuildConfig.WS_URL + "?token=" + token + "&roomToken=" + roomToken);
        client = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                Log.e("JWebSocketClientService", "收到的消息：" + message);
                if (message != null) {
                    try {
                        json = new JSONObject(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    msgType = json.optString("msgType");
                    isGet = json.optString("isGet");
                    if (isGet.equals("1")) {
                        msgList.clear();
                    }
                    if (msgType.equals("1") || msgType.equals("2")) {
                        showAlipay();//弹出充值或预授对话框
                    } else {
                        String userName = json.optString("userName");
                        if (null != userName && !TextUtils.isEmpty(userName)) {
                            msg = new Message();
                            msg.setActionTime(json.optString("actionTime"));
                            msg.setActionTimeStr(json.optString("actionTimeStr"));
                            msg.setAvatar(json.optString("avatar"));
                            msg.setBounty(json.optString("bounty"));
                            msg.setIsGet(json.optString("isGet"));
                            msg.setMsg(json.optString("msg"));
                            msg.setMsgType(json.optString("msgType"));
                            msg.setPrice(json.optString("price"));
                            msg.setRoomNo(json.optString("roomNo"));
                            msg.setRoomToken(json.optString("roomToken"));
                            msg.setUserId(json.optString("userId"));
                            msg.setUserName(json.optString("userName"));
                            msgList.add(msg);
                            showMessage();
                        }
                    }
                } else {
                    isconnet = false;
                }
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                Log.e("JWebSocketClientService", "websocket连接成功");
                isconnet = true;
                Map map = new HashMap();
                map.put("token", token);
                map.put("roomToken", roomToken);
                map.put("msgType", "2");
                String param = JSON.toJSONString(map);
                client.send(param);
            }

            @Override
            public void onError(Exception ex) {
                super.onError(ex);
                Log.e("JWebSocketClientService", "websocket出错");
                isconnet = false;
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                super.onClose(code, reason, remote);
                Log.e("JWebSocketClientService", "websocket关闭onClose");
                isconnet = false;
            }

            @Override
            public void onClosing(int code, String reason, boolean remote) {
                super.onClosing(code, reason, remote);
                Log.e("JWebSocketClientService", "websocket关闭onClosing");
            }
        };
        connect();
    }

    //ws必须切回主线程才可以更新ui
    private void showMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("msgList", "数据：" + json.optString("price"));
                try {
                    linPriceName.setVisibility(View.VISIBLE);
                    linPriceProduct.setVisibility(View.GONE);
                    //数据已重复
                    ImageUtil.displayImage(json.optString("avatar"), imamePriceHead);
                    tvPriceName.setText(json.optString("userName"));
                    tvPriceNow.setText("￥" + json.optString("price"));
                    tvPriceOne.setText("￥" + FastData.getGoodprice());
                    //当有新消息时，调用notifyItemInserted方法刷新listview中的显示
                    if (msgList.size() - 1 == 0) {
                        adapter.notifyDataSetChanged();
                    } else {
//                        adapter.notifyItemInserted(msgList.size() - 1);
                        adapter.notifyDataSetChanged();
                        //将listview定位到最后一行
                        recycleviewPrice.scrollToPosition(msgList.size() - 1);
                    }
                    if ("1".equals(isGet)) {
                        status = "3";
                        if (msg.getUserId().equals(token)) {
                            showHomeOrder();
                        }
                    }
                } catch (Exception e) {
                }
            }
        });
    }

    //展示无资格
    private void showAlipay() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msgType.equals("1")) {
                    showAuhn();
                }
            }
        });
    }

    /**
     * 连接websocket
     */
    private void connect() {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
                    Log.e("JWebSocketClientService", "websocket正在连接中");
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //connectBlocking多出一个等待操作，会先连接再发送，否则未连接发送会报错
//                    Log.e("JWebSocketClientService", "websocket正在连接中");
//                    client.connectBlocking();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    //    -------------------------------------websocket心跳检测------------------------------------------------
    private static final long HEART_BEAT_RATE = 30 * 1000;//每隔30秒进行一次对长连接的心跳检测
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            Log.e("JWebSocketClientService", "心跳包检测websocket连接状态");
            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }
            } else {
                //如果client已为空，重新初始化连接
                client = null;
                initSocketClient();
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.e("JWebSocketClientService", "开启重连");
                    client.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (client != null) {
            client.close();
        }
    }

//    //在onResume()方法注册
//    @Override
//    protected void onResume() {
//        if (netWorkStateReceiver == null) {
//            netWorkStateReceiver = new NetWorkStateReceiver();
//        }
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        registerReceiver(netWorkStateReceiver, filter);
//        super.onResume();
//    }

    @Override
    protected void onPause() {
        super.onPause();
//        unregisterReceiver(netWorkStateReceiver);
        quitRoom();
    }

    //离开拍场
    private void quitRoom() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("aid", goodId);
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().quit(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    /**
     * 支付宝预授权
     */
    private void auth() {
        recycleviewPrice.showLoading();
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().free(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    recycleviewPrice.finishLoading();
                    if (request.code.equals("200")) {
                        final String alipayInfo = request.data.body;
                        outTradeNo = request.data.outOrderNo;
                        FastData.setOutTradeNo(outTradeNo);
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(PriceActivity.this);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(alipayInfo, true);
                                android.os.Message msg = new android.os.Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandlers.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    recycleviewPrice.finishLoading();
                    Log.e(TAG, "error", throwable);
                });
    }

    private void AlipayQuery() {//预授权
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("outOrderNo", FastData.getOutTradeNo());
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().freeQuery(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    recycleviewPrice.finishLoading();
                    if (request.getCode().equals("200")) {
                        finish();
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    recycleviewPrice.finishLoading();
                    Log.e(TAG, "error", throwable);
                });
        MainActivity.openSingleTop(getCurrentActivity());
    }

    //监听网络变化，重连ws
    public class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            System.out.println("网络状态发生变化");
            //检测API是不是小于21，因为到了API21之后getNetworkInfo(int networkType)方法被弃用
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
                //获得ConnectivityManager对象
                ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                //获取ConnectivityManager对象对应的NetworkInfo对象
                //获取WIFI连接的信息
                NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                //获取移动数据连接的信息
                NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
                    msgList.clear();
                    adapter.notifyDataSetChanged();
                    initInto();
                } else if (wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
                    client.close();
                } else if (!wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
                    msgList.clear();
                    adapter.notifyDataSetChanged();
                    initInto();
                } else {
                    client.close();
                }
            } else {
                //这里的就不写了，前面有写，大同小异
                System.out.println("API level 大于21");
                //获得ConnectivityManager对象
                ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                //获取所有网络连接的信息
                Network[] networks = connMgr.getAllNetworks();
                //用于存放网络连接信息
                StringBuilder sb = new StringBuilder();
                //通过循环将网络信息逐个取出来
                for (int i = 0; i < networks.length; i++) {
                    //获取ConnectivityManager对象对应的NetworkInfo对象
                    NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                    sb.append(networkInfo.getTypeName() + " connect is " + networkInfo.isConnected());
                    msgList.clear();
                    adapter.notifyDataSetChanged();
                    initInto();
                }
            }
        }
    }
}
